 //
//  UserAccount.swift
//  weibo
//
//  Created by tomato on 2021/9/26.
//

import UIKit

@objcMembers

class UserAccount: NSObject,NSCoding{
    
    func encode(with coder: NSCoder) {
        
    }
    /// 用户授权的唯一票据
    var access_token: String?
    /// access_token的生命周期，单位是秒数, 基本数据类型不能使用?,KVC会找不到
    var expires_in: TimeInterval = 0 {
        didSet {
            //didSet方法可以进行监听值的改变
            // KVC给expires_in属性赋值完后,来创建expiresDate
            //OC中重写set方法
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    /// 授权用户的UID
    var uid: String?
    /// 过期时间, 方便比较时间
    var expiresDate: NSDate?
    /// 用户昵称
    var screen_name: String?
    /// 用户头像地址（大图），180×180像素, urlString
    var avatar_large: String?
    /// 通过字典来创建模型
    init(dict: [String: Any]) {
        super.init()
        // 对象创建好后才能使用对象的方法, 内部会调用setValue(value: AnyObject?, forKey key: String),每次拿一个key和value调用一次
        setValuesForKeys(dict)
        }
    
//    当setValue:forKey:找不到key时会调用setValue:forUndefinedKey:
//    如果不实现setValue:forUndefinedKey:就会报错
    override func setValue(_ value: Any?, forKey key: String) {
        super.setValue(value, forKey: key)
//        Print(items: "\(key) : \(value)")
    } 
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    func saveUserAccount() {
        //1、保存路径
        var path = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask, true).last!
        path = (path as NSString).appendingPathComponent("account.plist")
//        print("用户信息路径:\(path)")
        //2、归档保存
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    // MARK: - 归档和解档
//     解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        expires_in = aDecoder.decodeDouble(forKey: "expires_in")
        uid = aDecoder.decodeObject(forKey: "uid") as? String
        expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as? NSDate
        screen_name = aDecoder.decodeObject(forKey: "screen_name") as? String
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
    }
    
//     归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expires_in, forKey: "expires_in")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        aCoder.encode(screen_name, forKey: "screen_name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
    }
}

